/**
 * 
 */   
package com.gson.inter;  

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.gson.model.Weather;
import com.gson.model.WeatherData;
import com.gson.util.WeatherHandler;

/**   
 * @作者 Stone
 * @创建日期 2014-6-18 上午11:27:33
 * @版本 V1.0
 * @类说明
 */
public class BaiduWeatherService {

	/**
	 * 根据名称和作者搜索音乐
	 * 
	 * @param musicTitle 音乐名称
	 * @param musicAuthor 音乐作者
	 * @return Music
	 */
	public static Weather searchWeather(String cityName) {
		// 百度音乐搜索地址
		String requestUrl = "http://api.map.baidu.com/telematics/v3/weather?location={CITYNAME}&output=xml&ak=mGW8G2Gfg08CuO3bZBj6Iy9i";
		// 对音乐名称、作者进URL编码
		requestUrl = requestUrl.replace("{CITYNAME}", urlEncodeUTF8(cityName));
		// 处理名称、作者中间的空格
		requestUrl = requestUrl.replaceAll("\\+", "%20");

		// 查询并获取返回结果
		InputStream inputStream = httpRequest(requestUrl);
		// 从返回结果中解析出Music
		WeatherHandler handler = new WeatherHandler();
		Weather weather = handler.parseWeather(inputStream);

		return weather;
	}

	/**
	 * UTF-8编码
	 * 
	 * @param source
	 * @return
	 */
	private static String urlEncodeUTF8(String source) {
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 发送http请求取得返回的输入流
	 * 
	 * @param requestUrl 请求地址
	 * @return InputStream
	 */
	private static InputStream httpRequest(String requestUrl) {
		InputStream inputStream = null;
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoInput(true);
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			// 获得返回的输入流
			inputStream = httpUrlConn.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return inputStream;
	}

	// 测试方法
	public static void main(String[] args) {
		Weather weather = searchWeather("上海");
		System.out.println("结果状态：" + weather.getStatus());
		System.out.println("当前时间：" + weather.getDate());
		System.out.println("当前城市：" + weather.getCurrentCity());
		
		List<WeatherData> weatherDataList = weather.getResults();
		
		for (WeatherData weatherData : weatherDataList) {
			System.out.println("天气预报时间：" + weatherData.getDate());
			System.out.println("天气状况：" + weatherData.getWeather());
			System.out.println("风力：" + weatherData.getWind());
			System.out.println("温度：" + weatherData.getTemperature());
		}
	}

}
